package com.example.bank.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.bank.pojo.Client;
import com.example.bank.pojo.User;
import com.example.bank.service.client.ClientService;
import com.example.bank.service.image.ImageService;
import com.example.bank.service.union.UnionService;
import com.example.bank.service.user.UserService;
import com.example.bank.service.pdf.PDFReport;
import com.example.bank.util.ZipUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * @author ：Leeziqiang
 * @description：TODO
 * @date ：2021/12/20 19:41
 */
@Controller
@RequestMapping("/back")
public class BackController {

    private static final Logger logger = LoggerFactory.getLogger(BackController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private ClientService clientService;
    @Autowired
    private UnionService unionService;
    @Autowired
    private ImageService imageService;


    @GetMapping("/")
    public String index() {
        return "login";
    }

    // 后台管理员登录
    @PostMapping("/login")
    public ModelAndView login(HttpSession session, @RequestParam("username") String username, @RequestParam("password") String password) {
        User admin = userService.adminLogin(username, password);
        ModelAndView mv = new ModelAndView();
        if (admin != null) {
            logger.info("登录成功");
            session.setAttribute("admin", admin);
            mv.addObject("info", "ok");
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        mv.addObject("info", "账号或密码错误");
        mv.setViewName("login");
        logger.info("登陆失败");
        return mv;
    }

    // 进入首页
    @GetMapping("/index")
    public ModelAndView toIndex(HttpSession session) {
        Object obj = session.getAttribute("admin");
        ModelAndView mv = new ModelAndView();
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> users = userService.list();
        mv.setViewName("index");
        mv.addObject("users", users);
        return mv;
    }

    // 展示所有用户
    @PostMapping("/list")
    public ModelAndView list(HttpSession session) {
        Object obj = session.getAttribute("admin");
        ModelAndView mv = new ModelAndView();
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> users = userService.list();
        mv.setViewName("index");
        mv.addObject("users", users);
        return mv;
    }

    @PostMapping("/listAdmin")
    public ModelAndView listAdmin(HttpSession session) {
        Object obj = session.getAttribute("admin");
        ModelAndView mv = new ModelAndView();
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> users = userService.listAdministrator();
        mv.setViewName("index");
        mv.addObject("users", users);
        return mv;
    }

    // 展示所有经理
    @PostMapping("/listAgent")
    public ModelAndView listAgent(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> agents = userService.listAgent();

        mv.setViewName("index");
        mv.addObject("users", agents);
        return mv;
    }

    // 展示所有业务员
    @PostMapping("/listSalesmen")
    public ModelAndView listSalesmen(HttpSession session) {
        logger.info("lisSalesman");
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> salesmen = userService.listSalesman();
        mv.setViewName("index");
        mv.addObject("users", salesmen);
        return mv;
    }

    // 将业务员设置成区域经理
    @GetMapping("/assign/{id}/{bankArea}")
    public ModelAndView assign(@PathVariable String id, @PathVariable String bankArea, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (userService.assign(id, bankArea)) {
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }


    @GetMapping("/toAdministrator/{id}")
    public ModelAndView toAdministrator(@PathVariable String id, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (userService.toAdministrator(id)) {
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        return mv;
    }

    // 展示未绑定的业务员
    @GetMapping("/toBind/{id}/{username}/{role}")
    public ModelAndView toBind(@PathVariable String id, @PathVariable String username, @PathVariable String role, HttpSession session) {
        ModelAndView mv = new ModelAndView("bind");
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<User> users = userService.unBind(id);
        session.setAttribute("id", id);
        session.setAttribute("role", role);
        session.setAttribute("username", username);
        mv.addObject("users", users);
        return mv;
    }

    //（业务员管理员）绑定业务员
    @GetMapping("/bind/{userId}")
    public ModelAndView bind(@PathVariable String userId, HttpSession session) throws IOException {
        ModelAndView mv = new ModelAndView("bind");
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        String id = (String) session.getAttribute("id");
        boolean b = userService.bind(userId, id);
        if (b) {
            logger.info("成功");
        }
        List<User> users = userService.unBind(id );
        mv.addObject("users", users);
        return mv;
    }

    // 展示所有客户
    @GetMapping("/show")
    public ModelAndView showClient(HttpSession session) {
        Object obj = session.getAttribute("admin");
        ModelAndView mv = new ModelAndView();
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<Client> clients = clientService.listAll();
        for (Client client : clients) {
            client.setSalesman(clientService.findSalesman(client.getClientId()));
        }
        mv.addObject("clients", clients);
        mv.setViewName("tables");
        return mv;
    }

    // 展示业务员对应的客户
    @GetMapping("/listClients/{id}")
    public ModelAndView listClients(@PathVariable String id, HttpSession session) {
        ModelAndView mv = new ModelAndView("clients");
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<String> clientIds = unionService.getClientIds(id);
        // 获取客户列表
        if (ObjectUtil.isEmpty(clientIds)) {
            return mv;
        }
        List<Client> clients = clientService.listClients(clientIds);
        for (Client client : clients) {
            client.setSalesman(clientService.findSalesman(client.getClientId()));
        }
        mv.addObject("id1",id);
        mv.addObject("clients", clients);
        return mv;
    }

    // 生成PDF
    @GetMapping("/pdf/{clientId}")
    public void generatePDF(@PathVariable String clientId, HttpServletResponse response) throws Exception {
        logger.info("clientId:"+clientId);
        if (StrUtil.isEmpty(clientId)) {

        }
        Client client = clientService.findById(clientId);
        // 查询图片
        Map<String, List<String>> images = imageService.listNames(clientId);
        client.setImages(images);
        PDFReport.exportReport(client, response);
    }


    // 下载客户图片材料
    @GetMapping("/download/{clientId}")
    public void download(@PathVariable String clientId) throws IOException {
        List<String> urls = imageService.listByNumber(clientId);

        ZipUtil.downZip(urls, "pic");

    }

    // 根据条件查询客户
    @PostMapping("/query")
    public ModelAndView query(String salesman, String bankArea, Integer approvalState, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        List<Client> clients = clientService.query(salesman, bankArea, approvalState);
        for (Client client : clients) {
            if (client == null) {
                clients.remove(client);
                break;
            }
            client.setSalesman(clientService.findSalesman(client.getClientId()));
        }
        logger.info(clients.toString());
        mv.addObject("clients", clients);
        mv.setViewName("tables");
        return mv;
    }

    @GetMapping("/delete/{id}")
    public ModelAndView delete(@PathVariable String id, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (userService.deleteRole(id)) {
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }

    @GetMapping("/withdraw/{id}")
    public ModelAndView withdraw(@PathVariable String id, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (userService.withdrawPerm(id)) {
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }

    @PostMapping("/setName")
    public ModelAndView setRealName(String id, String realName, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (userService.setRealName(id, realName)) {
            List<User> users = userService.list();
            mv.addObject("users", users);
            mv.setViewName("index");
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }

    @GetMapping("/deleteClient1/{id}/{clientId}")
    public ModelAndView deleteClient1(@PathVariable String id, @PathVariable String clientId, HttpSession session) {
        ModelAndView mv = new ModelAndView("clients");
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (clientService.deleteClient(clientId)) {
            List<String> clientIds = unionService.getClientIds(id);
            // 获取客户列表
            if (ObjectUtil.isEmpty(clientIds)) {
                return mv;
            }
            List<Client> clients = clientService.listClients(clientIds);
            for (Client client : clients) {
                client.setSalesman(clientService.findSalesman(client.getClientId()));
            }
            mv.addObject("id1", id);
            mv.addObject("clients", clients);
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }

    @GetMapping("/deleteClient2/{id}")
    public ModelAndView deleteClient2(@PathVariable String id, HttpSession session) {
        ModelAndView mv = new ModelAndView();
        Object obj = session.getAttribute("admin");
        if (obj == null) {
            mv.setViewName("login");
            return mv;
        }
        if (clientService.deleteClient(id)) {
            List<Client> clients = clientService.listAll();
            for (Client client : clients) {
                client.setSalesman(clientService.findSalesman(client.getClientId()));
            }
            mv.addObject("clients", clients);
            mv.setViewName("tables");
            return mv;
        }
        mv.setViewName("404");
        return mv;
    }

}
